package com.hyfd.service.mp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.hyfd.common.BaseJson;
import com.hyfd.common.Page;
import com.hyfd.dao.mp.CardDao;
import com.hyfd.service.BaseService;

import net.sf.jxls.transformer.XLSTransformer;

@Service
public class CardSer extends BaseService{

	@Autowired
	CardDao cardDao;
	
	Logger log = Logger.getLogger(getClass());
	
	public String cardList(HttpServletRequest req){
		StringBuilder sb=new StringBuilder();
		try{
			Map<String, Object> m=getMaps(req); //封装前台参数为map
			Page p=getPage(m);//提取分页参数
			int total = cardDao.countCard(m);
			p.setCount(total);
			int pageNum=p.getCurrentPage();
			int pageSize=p.getPageSize();
			
			sb.append("{");
			sb.append(""+getKey("page")+":"+p.getCurrentPage()+",");
			sb.append(""+getKey("total")+":"+p.getNumCount()+",");
			sb.append(""+getKey("records")+":"+p.getCount()+",");
			sb.append(""+getKey("rows")+":"+"");
			
			PageHelper.startPage(pageNum, pageSize);//mybatis分页插件
			List<Map<String, Object>> dataList = cardDao.selectAll(m);
			String dataListJson=BaseJson.listToJson(dataList);
			sb.append(dataListJson);
			sb.append("}");
		}catch(Exception e){
			getMyLog(e,log);
		}
		
		return sb.toString();
	}
	
	/**
	 * 导出模板
	 * @author lks 2017年7月26日下午5:31:04
	 * @param request
	 * @param response
	 */
	public void exportCardTemp(HttpServletRequest request,HttpServletResponse response){
		String templatePath = request.getServletContext().getRealPath("/")+File.separator + "downloadFiles"+ File.separator+"cardTemp.xlsx";
		try{
			response.setContentType("application/x-excel;charset=utf-8");
	        response.setHeader("Content-Disposition", "attachment;filename=cardTemp.xlsx");
	        response.setCharacterEncoding("utf-8");
	        FileInputStream in = new FileInputStream(templatePath);
	        OutputStream os = response.getOutputStream();
	        int b;  
	        while((b = in.read())!= -1){  
	        	os.write(b);  
	        }  
	        os.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 导入卡密信息
	 * @author lks 2017年7月26日下午5:54:59
	 * @param request
	 * @param response
	 * @return
	 */
	public String importCard(HttpServletRequest request,HttpServletResponse response){
		JSONObject json = new JSONObject();
		int i = 0;
		String message = "请上传文件";
		try{
			DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
			Iterator<String> iterator = req.getFileNames();
			 while (iterator.hasNext()) {
	            MultipartFile file = req.getFile(iterator.next());
	            Workbook wb = new XSSFWorkbook(file.getInputStream());
				Sheet sheet = wb.getSheetAt(0);
				for(Row row : sheet){
					if(row.getRowNum() != 0){
						Map<String,Object> card = new HashMap<String,Object>();
						card.put("cardId", row.getCell(0).getStringCellValue());
						card.put("cardPass", row.getCell(1).getStringCellValue());
						card.put("expireTime", row.getCell(2).getDateCellValue());
						card.put("price", new Double(row.getCell(3).getNumericCellValue()).intValue());
						card.put("type", row.getCell(4).getStringCellValue());
						card.put("useState", 0);
						int x = cardDao.insertSelective(card);
						i = i + x;					
					}
				}
				message = "有"+i+"条卡密信息上传成功！";
			 }
		}catch(Exception e){
			message = "上传卡密出错";
			e.printStackTrace();
			log.error(e.getMessage());
		}
		json.put("message", message);
		return json.toJSONString();
	}
	
}
